/* Garbage collection - GC.h
 *
 * This is a simple memory manager. The idea is that each time something is created with the new operator,
 * the resulting pointer can be passed to a GarbageCollector instance through its add method.
 *
 * Later, after all the pointers that have been inserted are sure to have lost their usefullness,
 * the collect method will delete all the pointers, resulting in free memory.
 */

#ifndef __GarbageCollector__
#define __GarbageCollector__

#include <vector>

using namespace std;

class PointerWrapperBase {
    public:
    virtual ~PointerWrapperBase() {}
};

template <typename T> class PointerWrapper : public PointerWrapperBase {
    T * p;
    public:
    PointerWrapper(T * ptr) {
        p=ptr;
    }
    ~PointerWrapper() {
        delete p;
    }
};

class GarbageCollector {
    vector <PointerWrapperBase *> V;
    public:
    template <typename T> void add(T * ptr) {
        PointerWrapperBase * p = new PointerWrapper<T>(ptr);
        V.push_back(p);
    }
    void collect() {
        while(!V.empty()) {
            PointerWrapperBase * obj = V.back();
            V.pop_back();
            delete obj;
        }
    }
};

#endif
